from duetopia.register.models import DataSource, DataFormat, DataSet, TimePeriod
from duetopia.metadata.rdf import rdf_get_datasources
from django.contrib.gis import geos

def rdf_import(model):
	for attrs in rdf_get_datasources(model):
		dataset, created = DataSet.objects.get_or_create(**attrs["dataset"])
		attrs["dataset"] = dataset

		try:
			attrs["format"] = DataFormat.objects.get(name = attrs["format"])
		except DataFormat.DoesNotExist:
			print "not creating, no format", attrs["format"]
			continue
	
		if "start" in attrs and "end" in attrs:
			timespan = TimePeriod(dtstart = attrs["start"],
					      dtend = attrs["end"])
		elif "start" in attrs:
			timespan = TimePeriod(date = attrs["start"])
		elif "end" in attrs:
			timespan = TimePeriod(date = attrs["end"])
		else:
			timespan = None

		if "region" in attrs:
			geom = geos.fromstr(attrs["region"])
			attrs["extents"] = geom.envelope.buffer(0).wkt

		try:
			datasource = DataSource.objects.get(uri = attrs["uri"])
		except DataSource.DoesNotExist:
			datasource = DataSource()
		datasource.__dict__.update(attrs)
		datasource.dataset = attrs["dataset"] ## why?
		datasource.format = attrs["format"] ## why?

		if timespan:
			if not datasource.timespan:
				timespan.save()
				datasource.timespan = timespan
			else:
				timespan = datasource.timespan
			attrs["timespan"] = timespan

		try:
			datasource.save()
		except Exception, e:
			print "oops", e
			raise

		attrs["source"] = datasource
		
		yield attrs
